// threadtest.cc
//	Simple test case for the threads assignment.
//
//	Create two threads, and have them context switch
//	back and forth between themselves by calling Thread::Yield,
//	to illustratethe inner workings of the thread system.
//
// Copyright (c) 1992-1993 The Regents of the University of California.
// All rights reserved.  See copyright.h for copyright notice and limitation
// of liability and disclaimer of warranty provisions.

#include "copyright.h"
#include "system.h"

//----------------------------------------------------------------------
// SimpleThread
// 	Loop 5 times, yielding the CPU to another ready thread
//	each iteration.
//
//	"which" is simply a number identifying the thread, for debugging
//	purposes.
//----------------------------------------------------------------------

static void
priority(int which) {
    for(int i = 0; i < 10; i++) {
        printf("Thread %d got control, and has priority %d\n", which,
               which/8);
        currentThread->Yield();
    }
}

//----------------------------------------------------------------------
// ThreadTest
// 	Set up a ping-pong between two threads, by forking a thread
//	to call SimpleThread, and then calling SimpleThread ourselves.
//----------------------------------------------------------------------

void
ThreadTest() {
    int num_threads = 4;
    Thread* threads[num_threads];
    char* thread_names[num_threads];

    DEBUG('t', "Starting Heap Test");

    for(int i = 0; i < num_threads; i++) {
        //Note that this memory is never recovered.
        //It should be after a join on each thread, but
        //Thread doesn't support that (yet).
        thread_names[i] = new char[20];
        sprintf(thread_names[i], "Priority %d", i);
        threads[i] = new Thread(thread_names[i], i/8);
        threads[i]->Fork(priority, i);
    }
}
